// index.ts
// 获取应用实例
const app = getApp<IAppOption>()
import { list as getList, hasPermission, apply, getDirectoryTree } from '../../api/index'
Page({
  data: {
    navList: [],
    navCurrent: 0,
    list: [],
    avatarUrl: 1, nickName: 1,
    MenuData: [],
    articleData: [],
  },
  onLoad() {
    wx.showLoading({ title: '',mask: true })
    getDirectoryTree().then(res => {
      wx.hideLoading()
      this.setData({
				MenuData: res.data
			})
      const e = {
        target: {
          dataset:{
            index: 0
          }
        }
      }
      this.navClick(e)
		}).catch(err => {
      wx.hideLoading()
    })
  },
  toLogin() {
    wx.removeStorageSync('token')
    wx.reLaunch({url: '/pages/login/login'})
  },
  // 导航切换
  navClick(e: any) {
    const index = e.target.dataset.index
    const { MenuData } = this.data
    this.setData({
      navCurrent: index,
      articleData: []
    })

    if (MenuData[index]?.childList?.length) {
      let arr = []
      let idx_ = 0
      wx.showLoading()
      const fn = () => {
        getList({ directoryId: MenuData[index].childList[idx_].id, pageIndex: 1, pageSize: 10})
        .then(res => {
          arr.push({
            id: MenuData[index].childList[idx_].id,
            parentId: MenuData[index].childList[idx_].parentId,
            name: MenuData[index].childList[idx_].name,
            list: res.data.rows,
            total: res.data.total
          })
          idx_++;
          if (idx_ >= MenuData[index].childList.length) {
            this.setData({
              articleData: arr.filter(item => { return item.total })
            })
            wx.hideLoading()
            return
          }
          fn()
        }).catch(() => {
          idx_++;
          if (idx_ >= MenuData[index].childList.length) {
            this.setData({
              articleData: arr.filter(item => { return item.total })
            })
            wx.hideLoading()
            return
          }
          fn()
        })
      }
      fn()
    }
  },
  // 去服务流程
  toServiceProcess(e) {
    const id = e.currentTarget.dataset?.id || ''
    const title = e.currentTarget.dataset?.title || ''
    wx.navigateTo({
      url: `/pages/list/list?directoryId=${id}&title=${title}`,
    })
  },
  // 下载文件
  down(e) {
    const that = this
    if (!wx.getStorageSync('token')) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否登录？',
        showCancel: true,
        confirmText: '去登录',
        confirmColor: '#FFE501',
        success: ({ confirm, cancel }) => {
          if (confirm) {
            wx.redirectTo({ url: '/pages/login/login' })
          }
        }
      })
      return
    }
    const item = e.currentTarget.dataset.item
    if (item.accessStatus === 1) {
      wx.navigateTo({
        url: `/pages/detail/detail?id=${item.id}&accessStatus=1`
      })
      return
    }
    wx.showLoading({ title: '',mask: true })
    hasPermission({
      documentId: item.id
    }).then(res => {
      wx.hideLoading()
      if (!res.data) {
        wx.showModal({
          title: '提示',
          content: '暂无访问权限，是否申请授权？',
          showCancel: true,
          confirmColor: '#FFE501',
          success: ({ confirm, cancel }) => {
            if (confirm) {
              wx.showLoading({ title: '',mask: true })
              apply({ documentId:item.id }).then(res1 => {
                wx.hideLoading()
                wx.showToast({title: '权限已申请，审核通过后，我们会及时通知您！', icon: 'none'})
                that.subscriptionsSetting()
              }).catch(res => {
                wx.hideLoading()
                that.subscriptionsSetting()
                wx.showToast({title: res.errorMsg, icon: 'none'})
              })
            }
          }
        })
      } else {
        wx.navigateTo({
          url: `/pages/detail/detail?id=${item.id}`
        })
      }
    }).catch(err => {
      wx.hideLoading()
    })
  },
  // 订阅消息开启
  subscriptionsSetting() {
    wx.requestSubscribeMessage({
      tmplIds: ['Ew99D7BIEeUItIOnNNU7mgoGa1emqekDaGdOn63bDqw'],
      success (res) {
        console.log(res, 1)
      },
      fail (err) {
        console.log(err, 2)
      }
    })
    
    wx.getSetting({
      withSubscriptions: true,
      success (res) {
        console.log(res)
        if (res.subscriptionsSetting.mainSwitch && !res.subscriptionsSetting.itemSettings) {
          // wx.requestSubscribeMessage({
          //   tmplIds: ['Ew99D7BIEeUItIOnNNU7mgoGa1emqekDaGdOn63bDqw'],
          //   success (res) { }
          // })
        }
      }
    })
  },
  onShareAppMessage: function () {
    // 页面被用户分享时执行
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: 'EY汽车知识库，享你所想！'
        })
      }, 2000)
    })
    return {
      title: 'EY汽车知识库',
      path: '/page/index/index',
      promise 
    }
  },
  directoryClick(e) {
    this.down({
      currentTarget: {
        dataset: {
          item: e.detail
        }
      }
    })
  },
  menuClick() {
    this.selectComponent('#leftmenu').isShow()
  },
  // 去搜索页
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  }
})
